<template>
  <el-container class="main-container">
    <el-container>
      <el-container>
        <el-main>
          <div class="device-info">
            <!-- Toolbar -->
            <el-row class="toolbar">
              <el-row>
                <el-col :span="12" class="guidance-text" style="text-align: left;">
                  <p>请搜索来筛选停车场设备信息：</p>
                </el-col>
                <el-col :span="12" class="action-area" style="text-align: center;">
                  <el-button type="primary" icon="el-icon-map-location" @click="navigateTo('ParkingGuidances')">
                    To Parking Guidances
                  </el-button>
                  <el-button type="success" icon="el-icon-plus" @click="openAddDialog">
                    Add Device
                  </el-button>
                </el-col>
              </el-row>
              <el-col :span="24" class="search-area">
                <el-select v-model="searchForm.deviceType" placeholder="Search by Device Type" class="search-select"
                  clearable>
                  <el-option v-for="item in deviceTypeOptions" :key="item.value" :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
                <el-input v-model="searchForm.location" placeholder="Search by Location" class="search-input" clearable>
                </el-input>
                <el-select v-model="searchForm.status" placeholder="Select Status" class="search-select" clearable>
                  <el-option label="All" value=""></el-option>
                  <el-option label="Online" value="Online"></el-option>
                  <el-option label="Offline" value="Offline"></el-option>
                </el-select>
                <el-button type="primary" icon="el-icon-search" @click="filterDevices">Search</el-button>
              </el-col>
            </el-row>


            <!-- Device Table -->
            <el-table :data="currentDevices" stripe border :row-class-name="tableRowClassName">
              <el-table-column label="No." width="60" type="index" :index="calculateIndex" />
              <el-table-column prop="deviceId" label="Device ID" width="100" />
              <el-table-column prop="deviceType" label="Device Type" width="200" />
              <el-table-column prop="location" label="Location" />
              <el-table-column prop="status" label="Status" width="100" />
              <el-table-column label="Actions" width="180">
                <template slot-scope="scope">
                  <el-button size="small" type="text" @click="openEditDialog(scope.row)">Edit</el-button>
                  <el-button size="small" type="text" @click="deleteDevice(scope.row.deviceId)">Delete</el-button>
                </template>
              </el-table-column>
            </el-table>

            <!-- Pagination -->
            <el-pagination :current-page="currentPage" :page-size="pageSize" :total="totalDevices"
              @current-change="handlePageChange"></el-pagination>

            <!-- Add/Edit Dialog -->
            <el-dialog :title="dialogTitle" :visible.sync="dialogVisible">
              <el-form :model="deviceForm" label-width="120px">
                <el-form-item label="Device Type" style="text-align: left;">
                  <el-select v-model="deviceForm.deviceType" placeholder="Select Device Type">
                    <el-option label="Sensor" value="Sensor"></el-option>
                    <el-option label="Camera" value="Camera"></el-option>
                    <el-option label="Solid" value="Solid"></el-option>
                    <el-option label="Other" value="Other"></el-option>
                    <!-- 其他预定义类型 -->
                  </el-select>
                </el-form-item>
                <el-form-item label="Location">
                  <el-input v-model="deviceForm.location"></el-input>
                </el-form-item>
                <el-form-item label="Status" style="text-align: left;">
                  <el-select v-model="deviceForm.status" placeholder="Select Status">
                    <el-option label="Online" value="Online"></el-option>
                    <el-option label="Offline" value="Offline"></el-option>
                  </el-select>
                </el-form-item>
              </el-form>
              <div slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">Cancel</el-button>
                <el-button type="primary" @click="saveDevice">Save</el-button>
              </div>
            </el-dialog>
          </div>
          <!-- Information Cards -->
          <el-row class="info-cards" :gutter="20">
            <el-col :span="8">
              <el-card class="box-card">
                <div slot="header" class="clearfix">
                  <span>设备概览</span>
                </div>
                <div>
                  <p>设备名称：智慧停车场管理系统</p>
                  <p>设备型号：PMS-2024</p>
                  <p>设备编号：PARK-123456</p>
                  <p>安装日期：2024-01-01</p>
                  <p>维护周期：季度检查</p>
                </div>
              </el-card>
            </el-col>
            <el-col :span="8">
              <el-card class="box-card">
                <div slot="header" class="clearfix">
                  <span>操作规范</span>
                </div>
                <div>
                  <p>1. 遵循系统操作手册进行设备操作。</p>
                  <p>2. 定期检查传感器和摄像头连接，确保稳定。</p>
                  <p>3. 避免在恶劣天气下进行户外设备操作。</p>
                  <p>4. 遇到系统异常时立即停止使用，并联系技术支持。</p>
                  <p>5. 非授权人员禁止对设备进行任何形式的拆解。</p>
                </div>
              </el-card>
            </el-col>
            <el-col :span="8">
              <el-card class="box-card">
                <div slot="header" class="clearfix">
                  <span>维护保养</span>
                </div>
                <div>
                  <p>1. 保持设备表面清洁，定期清除灰尘和杂物。</p>
                  <p>2. 检查电源线和数据传输线路，防止磨损和损坏。</p>
                  <p>3. 定期进行软件更新，确保系统最新且安全。</p>
                  <p>4. 避免长时间在潮湿环境下存放或使用设备。</p>
                  <p>5. 每季度进行一次全面的设备检查和维护。</p>
                </div>
              </el-card>
            </el-col>
          </el-row>

        </el-main>
      </el-container>
    </el-container>
  </el-container>


</template>

<script>
import { getDevices, addDevice, updateDevice, deleteDevice } from '@/api/deviceInfo';
export default {
  name: 'DeviceInfo',

  data() {
    return {
      devices: [],
      currentDevices: [],
      totalDevices: 0,
      currentPage: 1,
      pageSize: 5,
      dialogVisible: false,
      dialogTitle: '',
      searchForm: {
        deviceType: '',
        location: '',
        status: ''
      },
      deviceForm: {
        deviceId: null,
        deviceType: '',
        location: '',
        status: ''
      },
      deviceTypeOptions: [
      { label: 'Sensor', value: 'Sensor' },
      { label: 'Camera', value: 'Camera' },
      { label: 'Solid', value: 'Solid' },
      { label: 'Other', value: 'Other' },
      // 其他预定义类型
    ],
    };
  },
  computed: {
    filteredDevices() {
      // 如果 devices 为空或未定义，返回空数组
      if (!Array.isArray(this.devices)) {
        return [];
      }
      return this.devices.filter((device) => {
        return (
          (!this.searchForm.deviceType || device.deviceType.includes(this.searchForm.deviceType)) &&
          (!this.searchForm.location || device.location.includes(this.searchForm.location)) &&
          (!this.searchForm.status || device.status === this.searchForm.status)
        );
      });
    }
  },

  methods: {
    // Navigate to another route
    navigateTo(routeName) {
      this.$router.push({ name: routeName }).catch(err => {
        if (err.name != 'NavigationDuplicated') {
          throw err;
        }
      }); // 跳转到对应路由
    },
    // Fetch devices from API
    fetchDevices() {
      getDevices().then((response) => {
        this.devices = response || []; // 确保 devices 是一个数组
        this.totalDevices = this.filteredDevices.length; // 使用过滤后的长度
        this.updateCurrentDevices();
      }).catch((error) => {
        console.error("Error fetching devices:", error);
        this.devices = [];
      });
    },
    // Update current page data
    updateCurrentDevices() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      this.currentDevices = this.filteredDevices.slice(start, end); // 基于过滤后的数据分页
      this.totalDevices = this.filteredDevices.length; // 更新总数为过滤后的数据长度
    },
    // Handle page change
    handlePageChange(page) {
      this.currentPage = page;
      this.updateCurrentDevices();
    },
    // Open dialog for adding a device
    openAddDialog() {
      this.dialogTitle = 'Add Device';
      this.deviceForm = { deviceId: null, deviceType: '', location: '', status: '' };
      this.dialogVisible = true;
    },
    // Open dialog for editing a device
    openEditDialog(device) {
      this.dialogTitle = 'Edit Device';
      this.deviceForm = { ...device };
      this.dialogVisible = true;
    },
    // Save device
    saveDevice() {
      const apiCall = this.deviceForm.deviceId ? updateDevice : addDevice;
      apiCall(this.deviceForm).then(() => {
        this.fetchDevices();
        this.dialogVisible = false;
      });
    },
    // Delete device
    deleteDevice(deviceId) {
      this.$confirm('Are you sure to delete this device?', 'Warning', {
        confirmButtonText: 'Yes',
        cancelButtonText: 'No',
        type: 'warning'
      }).then(() => {
        deleteDevice(deviceId).then(() => {
          this.fetchDevices();
        });
      });
    },
    // Highlight rows based on status
    tableRowClassName({ row }) {
      return row.status === 'Offline' ? 'offline-row' : '';
    },
    // Filter devices based on search criteria
    filterDevices() {
      this.currentPage = 1;// 重置到第一页
      this.updateCurrentDevices();// 重新更新显示的设备列表
    },
    // Calculate index for sequence number
    calculateIndex(index) {
      return (this.currentPage - 1) * this.pageSize + index + 1;
    }
  },
  mounted() {
    this.fetchDevices();
  }
};
</script>

<style>
.main-container {
  margin-left: 200px;
  margin-top: 100px;
}

.toolbar {
  margin-bottom: 20px;
  padding: 10px;
  background-color: #f9f9f9;
  border-radius: 8px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.search-area {
  display: flex;
  align-items: center;
  gap: 10px;
  /* 增加组件间的间距 */
}

.search-input {
  width: 200px;
  /* 输入框宽度 */
}

.search-select {
  width: 150px;
  /* 下拉框宽度 */
}

.action-area .el-button {
  margin-left: 10px;
  /* 按钮间距 */
}

.info-cards {
  margin-top: 20px;
}


.el-card__header {
  padding: 15px;
  background-color: #f9f9f9;
  border-bottom: 1px solid #ebeef5;
}

.el-card__body {
  padding: 15px;
}

.box-card {
  transition: transform 0.3s ease-in-out, box-shadow 0.3s ease-in-out;
  cursor: pointer;
  margin-bottom: 20px;
}

.box-card:hover {
  transform: scale(1.05);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.2);
}
</style>
